package com.springframework.boot.shiro.realm;

import com.springframework.boot.common.perms.entity.Perms;
import com.springframework.boot.common.user.entity.User;
import com.springframework.boot.common.user.service.UserService;
import com.springframework.boot.shiro.salt.ByteSourceSerializable;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
//自定义realm
public class CustomerRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取主身份信息
        String primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
        log.info(String.format("调用授权验证：%s",primaryPrincipal));
        //根据主身份信息获取角色和权限信息
        User user = userService.getRolesByUsername(primaryPrincipal);
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo =new SimpleAuthorizationInfo();
            user.getRoles().forEach(role->{
                simpleAuthorizationInfo.addRole(role.getName());

                //权限信息
                List<Perms> perms = userService.getPermsByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(perms)){
                    perms.forEach(perm->{
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }
            });
            return simpleAuthorizationInfo;
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.debug("=============认证===========");
        String username = (String)token.getPrincipal();
        //根据用户名查询数据库
        User user = userService.getUserByUsername(username);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), new ByteSourceSerializable(user.getSalt()),this.getName());
        }
        return null;
    }
}
